package org.jeecg.modules.quality.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.modules.erp.base.service.IErpWarehouseService;
import org.jeecg.modules.inventory.entity.BussInventoryDetails;
import org.jeecg.modules.inventory.mapper.BussInventoryDetailsMapper;
import org.jeecg.modules.inventory.mapper.BussInventoryInoutDetailsMapper;
import org.jeecg.modules.inventory.mapper.BussInventoryMapper;
import org.jeecg.modules.inventory.mapper.BussInventoryPurchaseOrderMapper;
import org.jeecg.modules.inventory.service.IBussInventoryDetailsService;
import org.jeecg.modules.outbound.entity.BussOutboundOrderDetail;
import org.jeecg.modules.outbound.mapper.BussOutboundOrderDetailMapper;
import org.jeecg.modules.procurement.mapper.BussMaterialProcurementDetailMapper;
import org.jeecg.modules.procurement.mapper.BussMaterialProcurementMapper;
import org.jeecg.modules.quality.entity.BussInspectionForm;
import org.jeecg.modules.quality.entity.BussInspectionFormDetail;
import org.jeecg.modules.quality.entity.BussInspectionFormStorage;
import org.jeecg.modules.quality.entity.BussUnqualifiedForm;
import org.jeecg.modules.quality.mapper.BussInspectionFormDetailMapper;
import org.jeecg.modules.quality.mapper.BussInspectionFormMapper;
import org.jeecg.modules.quality.mapper.BussInspectionFormStorageMapper;
import org.jeecg.modules.quality.mapper.BussUnqualifiedFormMapper;
import org.jeecg.modules.quality.service.IBussInspectionFormService;
import org.jeecg.modules.quality.vo.BussInspectionFormDetailVo;
import org.jeecg.modules.quality.vo.BussInspectionFormPage;
import org.jeecg.modules.quality.vo.BussInspectionFormStorageVo;
import org.jeecg.modules.storage.entity.BussStorageNotice;
import org.jeecg.modules.storage.entity.BussStorageNoticeMaterial;
import org.jeecg.modules.storage.mapper.BussStorageDetailMapper;
import org.jeecg.modules.storage.mapper.BussStorageNoticeMapper;
import org.jeecg.modules.storage.mapper.BussStorageNoticeMaterialMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * @Description: 检验单
 * @Author: jeecg-boot
 * @Date:   2024-07-09
 * @Version: V1.0
 */
@Service
public class BussInspectionFormServiceImpl extends ServiceImpl<BussInspectionFormMapper, BussInspectionForm> implements IBussInspectionFormService {

	@Autowired
	private BussInspectionFormMapper bussInspectionFormMapper;
	@Autowired
	private BussInspectionFormStorageMapper bussInspectionFormStorageMapper;
	@Autowired
	private BussInspectionFormDetailMapper bussInspectionFormDetailMapper;
	@Autowired
	private BussStorageDetailMapper bussStorageDetailMapper;
	@Autowired
	private BussUnqualifiedFormMapper bussUnqualifiedFormMapper;
	@Autowired
	private BussInventoryDetailsMapper bussInventoryDetailsMapper;
	@Autowired
	private IBussInventoryDetailsService iBussInventoryDetailsService;
	@Autowired
	private BussStorageNoticeMaterialMapper bussStorageNoticeMaterialMapper;

	@Autowired
	private BussStorageNoticeMapper bussStorageNoticeMapper;
	@Autowired
	private IErpWarehouseService erpWarehouseService;
	@Autowired
	private BussInventoryMapper bussInventoryMapper;
	@Autowired
	private BussInventoryPurchaseOrderMapper bussInventoryPurchaseOrderMapper;
	@Autowired
	private BussInventoryInoutDetailsMapper bussInventoryInoutDetailsMapper;
	@Autowired
	private BussMaterialProcurementDetailMapper bussMaterialProcurementDetailMapper;
	@Autowired
	private BussMaterialProcurementMapper bussMaterialProcurementMapper;
	@Autowired
	private BussOutboundOrderDetailMapper bussOutboundOrderDetailMapper;
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveMain(BussInspectionForm bussInspectionForm, List<BussInspectionFormStorageVo> bussInspectionFormStorageList, List<BussInspectionFormDetailVo> bussInspectionFormDetailList, HttpServletRequest req,String storageDetailIds) {
		bussInspectionForm.setStatus("1");//默认已审批
		bussInspectionFormMapper.insert(bussInspectionForm);
		//todo 入库类型检验优化for循环内数据库交互未完成
		if(bussInspectionFormStorageList!=null && !bussInspectionFormStorageList.isEmpty()) {
			for(BussInspectionFormStorageVo entity:bussInspectionFormStorageList) {
				entity.setId(null);
				BussInspectionFormStorage storage = new BussInspectionFormStorage();
				BeanUtils.copyProperties(entity, storage);
				//外键设置
				storage.setInspectionId(bussInspectionForm.getId());
				bussInspectionFormStorageMapper.insert(storage);
				storageQcStatus(storage.getStorageDetailId(), bussInspectionForm.getInspectionResults(),bussInspectionForm.getId());
			}
		}
		if(bussInspectionFormDetailList!=null && bussInspectionFormDetailList.size()>0) {
			for(BussInspectionFormDetailVo entity:bussInspectionFormDetailList) {
				entity.setId(null);
				BussInspectionFormDetail detail = new BussInspectionFormDetail();
				BeanUtils.copyProperties(entity, detail);
				//外键设置
				detail.setInspectionId(bussInspectionForm.getId());
				bussInspectionFormDetailMapper.insert(detail);
			}
		}
		//不合格生成不合格处理单
		if (bussInspectionForm.getInspectionResults().equals("2")){
			saveUnqualified(bussInspectionForm.getId(),bussInspectionForm.getInspectionType(),req);
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateMain(BussInspectionForm bussInspectionForm,List<BussInspectionFormStorageVo> bussInspectionFormStorageList,List<BussInspectionFormDetailVo> bussInspectionFormDetailList) {
		bussInspectionForm.setStatus("1");//默认已审批
		bussInspectionFormMapper.updateById(bussInspectionForm);
		
		//1.先删除子表数据
		bussInspectionFormStorageMapper.deleteByMainId(bussInspectionForm.getId());
		bussInspectionFormDetailMapper.deleteByMainId(bussInspectionForm.getId());
		
		//2.子表数据重新插入
		if(bussInspectionFormStorageList!=null && bussInspectionFormStorageList.size()>0) {
			for(BussInspectionFormStorageVo entity:bussInspectionFormStorageList) {
				entity.setId(null);
				BussInspectionFormStorage storage = new BussInspectionFormStorage();
				BeanUtils.copyProperties(entity, storage);
				//外键设置
				storage.setInspectionId(bussInspectionForm.getId());
				bussInspectionFormStorageMapper.insert(storage);
				storageQcStatus(storage.getStorageDetailId(),bussInspectionForm.getInspectionResults(),bussInspectionForm.getId());
			}
		}
		if(bussInspectionFormDetailList!=null && bussInspectionFormDetailList.size()>0) {
			for(BussInspectionFormDetailVo entity:bussInspectionFormDetailList) {
				entity.setId(null);
				BussInspectionFormDetail detail = new BussInspectionFormDetail();
				BeanUtils.copyProperties(entity, detail);
				//外键设置
				detail.setInspectionId(bussInspectionForm.getId());
				bussInspectionFormDetailMapper.insert(detail);
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delMain(String id) {
		BussInspectionForm bussInspectionForm = bussInspectionFormMapper.selectById(id);
		//删除已审核的数据
		if(bussInspectionForm.getStatus().equals("1")){
			Collection<String> stringCollection = new ArrayList<>();
			stringCollection.add(id);
			//修改状态
			this.revokeBatch(stringCollection);
		}
//		bussInspectionFormStorageMapper.deleteByMainId(id);
//		bussInspectionFormDetailMapper.deleteByMainId(id);
//		bussInspectionFormMapper.deleteById(id);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			BussInspectionForm bussInspectionForm = bussInspectionFormMapper.selectById(id);
			//删除已审核的数据
			if(bussInspectionForm.getStatus().equals("1")){
				Collection<String> stringCollection = new ArrayList<>();
				stringCollection.add(id.toString());
				//修改状态
				this.revokeBatch(stringCollection);
			}
//		bussInspectionFormStorageMapper.deleteByMainId(id);
//		bussInspectionFormDetailMapper.deleteByMainId(id);
//		bussInspectionFormMapper.deleteById(id);
		}
	}

	@Override
	public IPage<BussInspectionFormPage> myPage(Page<BussInspectionForm> page, QueryWrapper<BussInspectionForm> queryWrapper) {
		return bussInspectionFormMapper.myPage(page,queryWrapper);
	}


	public void storageQcStatus(String id,String inspectionResults,String inspectionId){
		//修改入库单明细的质检状态
		BussStorageNoticeMaterial detail = bussStorageNoticeMaterialMapper.selectById(id);
		if (detail != null){
			this.updateStorageQc(detail,inspectionResults);
			//入库明细找库存明细，改状态
			List<BussInventoryDetails> inventoryDetails = bussInventoryDetailsMapper.selectByNoticeMaterial(detail.getId());
			if (inventoryDetails != null && inventoryDetails.size()>0){
				for (BussInventoryDetails details : inventoryDetails) {
					details.setQualityInspectionStatus(inspectionResults);
					details.setInspectionId(inspectionId);
					bussInventoryDetailsMapper.updateById(details);
				}
			}
		}
	}
	public void saveUnqualified(String id,String inspectionType,HttpServletRequest req){
		BussUnqualifiedForm form = new BussUnqualifiedForm();
		form.setInspectionId(id);
		form.setStatus("1");
		form.setInspectionType(inspectionType);
		String username = JwtUtil.getUserNameByToken(req);
		form.setCreateBy(username);
		form.setCreateTime(new Date());
		//todo 赋值编号
//		form.setCode("code");
		bussUnqualifiedFormMapper.insert(form);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void revokeBatch(Collection<? extends Serializable> idList) {
		for (Serializable id : idList) {
			queryOutboundStatus(id.toString());
//			BussInspectionForm form = bussInspectionFormMapper.selectById(id);
//			form.setStatus("0");
//			form.setInspectionResults("0");
//			bussInspectionFormMapper.updateById(form);
			//查询质检入库明细
			List<BussInspectionFormStorageVo> formStorages = bussInspectionFormStorageMapper.selectByMainId(id.toString());
			for (BussInspectionFormStorageVo storageVo : formStorages){
				//清空入库明细的质检状态
				BussStorageNoticeMaterial detail = bussStorageNoticeMaterialMapper.selectById(storageVo.getStorageDetailId());
				if (detail != null){
					this.revokeStorageQc(detail,"0");
					//通过入库明细Id找库存明细
					List<BussInventoryDetails>  inventoryDetails = bussInventoryDetailsMapper.selectByNoticeMaterial(detail.getId());
					if (inventoryDetails != null){
						for (BussInventoryDetails details : inventoryDetails) {
							details.setQualityInspectionStatus("0");
							bussInventoryDetailsMapper.updateById(details);
						}
					}
				}
			}
//撤销直接删除质检单
			bussInspectionFormStorageMapper.deleteByMainId(id.toString());
			bussInspectionFormDetailMapper.deleteByMainId(id.toString());
			bussInspectionFormMapper.deleteById(id.toString());
		}
	}

	/**
	 * 修改入库单状态
	 * @param material
	 * @param inspectionResults
	 */
	private void updateStorageQc(BussStorageNoticeMaterial material,String inspectionResults){
		material.setQcStatus(inspectionResults);
		bussStorageNoticeMaterialMapper.updateById(material);
		Long aLong = bussStorageNoticeMaterialMapper.selectCount(new LambdaQueryWrapper<BussStorageNoticeMaterial>()
				.eq(BussStorageNoticeMaterial::getNoticeId, material.getNoticeId()).eq(BussStorageNoticeMaterial::getQcStatus, "0"));
		if(aLong == 0){
			bussStorageNoticeMapper.update(null,
					new LambdaUpdateWrapper<BussStorageNotice>().eq(BussStorageNotice::getId, material.getNoticeId())
							.set(BussStorageNotice::getStatus, 2));
		}
	}

	/**
	 * 撤销 -修改入库单状态
	 * @param material
	 * @param inspectionResults
	 */
	private void revokeStorageQc(BussStorageNoticeMaterial material,String inspectionResults){
		material.setQcStatus(inspectionResults);
		bussStorageNoticeMaterialMapper.updateById(material);
		Long aLong = bussStorageNoticeMaterialMapper.selectCount(new LambdaQueryWrapper<BussStorageNoticeMaterial>()
				.eq(BussStorageNoticeMaterial::getNoticeId, material.getNoticeId()).ne(BussStorageNoticeMaterial::getQcStatus, "0"));
		if(aLong == 0){
		bussStorageNoticeMapper.update(null,
				new LambdaUpdateWrapper<BussStorageNotice>().eq(BussStorageNotice::getId, material.getNoticeId())
						.set(BussStorageNotice::getStatus, 0));
		}
	}

	public void queryOutboundStatus(String id){

		//通过质检查询质检明细对应的入库明细
		List<BussInspectionFormStorageVo> formStorage = bussInspectionFormStorageMapper.selectByMainId(id);
		for (BussInspectionFormStorageVo storageVo : formStorage){
			BussStorageNoticeMaterial detail = bussStorageNoticeMaterialMapper.selectById(storageVo.getStorageDetailId());
			if (detail != null){
				//已审核的出库明细中存不存在对应的入库单
				BussStorageNotice notice = bussStorageNoticeMapper.selectById(detail.getNoticeId());
				List<BussOutboundOrderDetail> outboundOrderDetails = bussOutboundOrderDetailMapper.selectByStorage(detail.getNoticeId());
				if (outboundOrderDetails != null && outboundOrderDetails.size()>0){
					throw new RuntimeException("质检明细中物料存在已审核的出库记录，不允许操作!");
				}
				//通过入库信息找库存明细
//				List<BussInventoryDetails> inventoryDetails = bussInventoryDetailsMapper.selectByNoticeMaterial(detail.getId());
//				if (inventoryDetails != null){
//					for (BussInventoryDetails details : inventoryDetails) {
//						//查询库存明细对应的已审核出库明细 如果有提示
//						List<BussOutboundOrderDetail> outboundOrderDetails = bussOutboundOrderDetailMapper.selectByInventory(details.getId());
//						if (outboundOrderDetails != null && outboundOrderDetails.size() > 0) {
//							throw new RuntimeException("质检明细中物料存在已审核的出库记录，不允许操作!");
//						}
//					}
//				}else {
//					throw new RuntimeException("质检后库存明细发生过变更，不允许操作!");
//				}
			}
		}
	}
}
